<!-- 想定构建_包括兵力部署、节点配置、任务配置、规则配置 -->
<template>
    <div class="scenario-build-container">
        <div class="scenario-build-container-top">
            <div class="scenario-build-container-top_item" style="color: var(--app-primary-base);"
                @click="handleConfigClick('intelligentAdvisor')">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.scenarioEdit.intelligentAdvisor") }}</div>
            </div>
            <div class="scenario-build-container-top_item" @click="handleConfigClick('nodeConfig')">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.scenarioEdit.nodeConfig") }}</div>
            </div>
            <div class="scenario-build-container-top_item" @click="handleConfigClick('taskConfig')">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.scenarioEdit.taskConfig") }}</div>
            </div>
            <div class="scenario-build-container-top_item" @click="handleConfigClick('ruleConfig')">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.scenarioEdit.ruleConfig") }}</div>
            </div>
            <div class="scenario-build-container-top_item" @click="$router.go(-1)">
                <svg-icon icon-class="folder" width="14" height="14" />
                <div class="title-word">{{ $t("tool.scenarioEdit.return") }}</div>
            </div>

        </div>

        <div class="scenario-build-container-bottom">
            <!-- 左侧树结构 -->
            <div class="s-b-left flex flex-col">
                <div class="w-full flex items-center" style="gap: 4px">
                    <el-input class="jtyj-input" prefix-icon="el-icon-search" v-model="queryContent"
                        @input="handleTreeFilter" clearable></el-input>
                    <el-badge :value="filterNum" class="item" :hidden="filterNum == 0">
                        <el-popover placement="top" :title="$t('tool.rightMenu.showFilter')" trigger="hover">
                            <el-button slot="reference" class="jtyj-btn-s" type="info" style="width: 32px; height: 32px"
                                @click="openFilter">
                                <span role="img" class="appIcon">
                                    <svg-icon icon-class="filter" width="16" height="16" />
                                </span>
                            </el-button>
                        </el-popover>
                    </el-badge>
                </div>
                <div class="filer-box" :class="isFilterOpen ? '' : 'hidden-height'">
                    <div class="filter-item">
                        <el-select v-model="filters.status" clearable placeholder="状态" class="jtyj-select">
                            <el-option label="启用" value="enabled"></el-option>
                            <el-option label="禁用" value="disabled"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <el-select v-model="filters.tags" clearable placeholder="标签" class="jtyj-select">
                            <el-option label="标签1" value="tag1"></el-option>
                            <el-option label="标签2" value="tag2"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <el-select v-model="filters.owner" clearable placeholder="责任人" class="jtyj-select">
                            <el-option label="张三" value="zhangsan"></el-option>
                            <el-option label="李四" value="lisi"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <el-select v-model="filters.creator" clearable placeholder="创建人" class="jtyj-select">
                            <el-option label="张三" value="zhangsan"></el-option>
                            <el-option label="李四" value="lisi"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <el-select v-model="filters.lastModifier" clearable placeholder="最后修改人" class="jtyj-select">
                            <el-option label="张三" value="zhangsan"></el-option>
                            <el-option label="李四" value="lisi"></el-option>
                        </el-select>
                    </div>
                    <div class="filter-item">
                        <el-radio-group class="common-radio-group" v-model="filters.matchType" size="mini">
                            <el-radio-button label="匹配"></el-radio-button>
                            <el-radio-button label="排除"></el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <div class="s-b-left-content">
                    <!-- 红方树 -->
                    <div class="ui-tree-node-title" @click="showRedTree = !showRedTree">
                        <div class="ui-tree-node-title__content">
                            <svg-icon icon-class="folder" width="16" height="16" />
                            <div class="title-word">红方实体</div>
                            <svg-icon icon-class="triangle-right-medium"
                                :style="showRedTree ? 'transform: rotate(90deg)' : ''" width="16" height="16" />
                        </div>
                        <div class="ui-tree-node-title__operate">
                            <el-popover class="ui-tree-node-title__operate-item" placement="top"
                                :title="$t('tool.rightMenu.addEntity')" trigger="hover">
                                <div slot="reference" class="item-icon loc-center"
                                    @click.stop="addEntityFromTitle('red')">
                                    <span role="img" class="appIcon">
                                        <svg-icon icon-class="create" width="10" height="10" />
                                    </span>
                                </div>
                            </el-popover>
                        </div>

                    </div>
                    <div class="ui-tree-node-content" v-show="showRedTree && redEntityTreeData.length > 0">
                        <Tree ref="scenarioBuildRedTreeRef" :isGlobalDataModeling="true" :topQuery="false"
                            :defaultExpandedKeys="defaultExpandedKeys" :currentNodeKey="currentNodeKey"
                            :treeData="redEntityTreeData" :fileMenu="right_menuList.rightMenuList_4"
                            @handleMenuClick="handleMenuClick" @nodeClick="nodeClick" @moveNodeOrder="moveNodeOrder">
                        </Tree>
                    </div>

                    <!-- 蓝方树 -->
                    <div class="ui-tree-node-title" @click="showBlueTree = !showBlueTree">
                        <div class="ui-tree-node-title__content">

                            <svg-icon icon-class="folder" width="16" height="16" />
                            <div class="title-word">蓝方实体</div>
                            <svg-icon icon-class="triangle-right-medium"
                                :style="showBlueTree ? 'transform: rotate(90deg)' : ''" width="16" height="16" />
                        </div>
                        <div class="ui-tree-node-title__operate">
                            <el-popover class="ui-tree-node-title__operate-item" placement="top"
                                :title="$t('tool.rightMenu.addEntity')" trigger="hover">
                                <div slot="reference" class="item-icon loc-center"
                                    @click.stop="addEntityFromTitle('blue')">
                                    <span role="img" class="appIcon">
                                        <svg-icon icon-class="create" width="10" height="10" />
                                    </span>
                                </div>
                            </el-popover>
                        </div>
                    </div>
                    <div class="ui-tree-node-content" v-show="showBlueTree && blueEntityTreeData.length > 0">
                        <Tree ref="scenarioBuildBlueTreeRef" :isGlobalDataModeling="true" :topQuery="false"
                            :defaultExpandedKeys="defaultExpandedKeys" :currentNodeKey="currentNodeKey"
                            :treeData="blueEntityTreeData" :fileMenu="right_menuList.rightMenuList_4"
                            @handleMenuClick="handleMenuClick" @nodeClick="nodeClick" @moveNodeOrder="moveNodeOrder">
                        </Tree>
                    </div>
                </div>

            </div>

            <!-- 中间地图 -->
            <div class="s-b-middle">
                <MarsMap :url="configUrl" @onload="onMapload"></MarsMap>
            </div>
            <!-- 右侧信息 -->
            <div class="s-b-right">
                <!-- 实体信息 -->
                <EntityInfo v-if="showEntityInfo" :nodeInfo="selectedNodeInfo" @submit="submitEntityInfo"></EntityInfo>
                <!-- 智能顾问 -->
                <IntelligentAdvisor v-if="showIntelligentAdvisor" @close="closeIntelligentAdvisor"></IntelligentAdvisor>

            </div>
        </div>

        <AddEntityDialog ref="addEntityDialog" @submit="addEntityToTree"/>
        <NodeConfigDialog ref="nodeConfigDialog" :scenarioId="scenarioId"></NodeConfigDialog>
        <TaskConfigDialog ref="taskConfigDialog"></TaskConfigDialog>
        <RuleConfigDialog ref="ruleConfigDialog"></RuleConfigDialog>
    </div>
</template>
<script>
import { getEntityTree } from "@/api/myspace/scenario-edit-tool/scenario-edit";
import Tree from "@/components/LeftTree/tree.vue";
import AddEntityDialog from "./components/deploy-entity/add-entity-dialog.vue";
import IntelligentAdvisor from "./components/intelligent-advisor/intelligent-advisor.vue";
import NodeConfigDialog from "./components/node-config/node-config-dialog.vue";
import TaskConfigDialog from "./components/task-config/task-config-dialog.vue";
import RuleConfigDialog from "./components/rule-config/rule-config-dialog.vue";
import EntityInfo from "./components/deploy-entity/entity-info.vue";
import MarsMap from "@/views/common-components/mars-map.vue";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
    name: "ScenarioBuild",
    data() {
        const basePathUrl = window.basePathUrl || ''
        return {
            configUrl: basePathUrl + '/config/map.json',
            queryContent: "",
            defaultExpandedKeys: [], //树默认要展开的节点
            currentNodeKey: 0,
            isFilterOpen: false,
            filters: {
                status: "",
                tags: "",
                owner: "",
                creator: "",
                lastModifier: "",
                matchType: "include",
            },
            selectedNodeInfo: null, //  当前选中节点的信息
            redEntityTreeData: [],
            blueEntityTreeData: [],
            showRedTree: true, // 显示红方树
            showBlueTree: true, // 显示蓝方树
            showEntityInfo: true, // 显示实体信息
            showIntelligentAdvisor: false, // 显示智能参谋
            scenarioId: 0,
            onlineIconAndModel: {
                model: {},
                modelScaling: {},
            },
            model3dModel: {},  // 值格式：{<entityType>: {model:"http://127.0.0.1/xx"}, scale: 10}
            modelVisualizationTag: {},  // 值格式：{<entityType>: 'radar'}
        };
    },
    components: {
        Tree,
        AddEntityDialog,
        EntityInfo,
        MarsMap,
        IntelligentAdvisor,
        NodeConfigDialog,
        TaskConfigDialog,
        RuleConfigDialog
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.scenarioEditTool.right_menuList,
            userId: (state) => state.user.id,
        }),
        filterNum() {
            return Object.values(this.filters).filter((item) => item).length - 1;
        },
    },
    async created() {
        // 获取 query 中的 scenarioId
        this.scenarioId = Number(this.$route.query.scenarioId);
        if (this.scenarioId == undefined) {
            console.warn('未检测到 scenarioId 参数');
            return;
        }
        console.log('接收到的 scenarioId:', this.scenarioId);
        // 同时获取 模型的3dModel、模型可视化标签、实体树、
        await Promise.all([
            this.getModel3dModel(),
            this.getModelVisualizationTag(),
            this.getEntityTree(),
        ]);
        // 添加实体到地图
        this.addEntityToMap();

    },
    mounted() {

    },
    methods: {
        // 打开过滤选项
        openFilter() {
            this.isFilterOpen = !this.isFilterOpen;
        },
        // 树过滤搜索
        handleTreeFilter(value) {
            console.log(value);
            this.$refs.scenarioBuildRedTreeRef.$refs.treeRef.filter(value);
            this.$refs.scenarioBuildBlueTreeRef.$refs.treeRef.filter(value);
        },

        // 从标题添加实体
        addEntityFromTitle(role) {
            this.$refs.addEntityDialog.dialogVisible = true;
        },

        nodeClick(node) {
            this.selectedNodeInfo = node;
            // 下面这三个赋值是用于点击[去编辑该数据模型]按钮时，让节点展开并选中
            // this.defaultExpandedKeys = Array.from(new Set([...this.defaultExpandedKeys, node.id]))
            // this.currentNodeKey = node.id;
            // this.$refs.scenarioBuildTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey)
        },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            globalDataMoveTreeNode({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getSelfGlobalDataTree();
                }
            });
        },

        // 复制
        handleCopy(node) {
            console.log("复制", node);
        },

        // 删除
        handleDelete(node) {
            console.log("删除", node);
        },

        // 菜单点击
        handleMenuClick(menu, node) {
            console.log(menu);

            switch (menu.name) {
                case "添加实体":
                    this.$refs.addEntityDialog.dialogVisible = true;
                    break;
                case "复制":
                    this.handleCopy(node);
                    break;
                case "删除":
                    this.handleDelete(node);
                    break;
            }
        },

        // 地图构造完成回调
        onMapload(map) {
            console.log(map);
        },

        // 处理节点配置、任务配置、规则配置的点击
        handleConfigClick(configName) {
            if (configName == 'intelligentAdvisor') {
                this.showIntelligentAdvisor = true;
                this.showEntityInfo = false;
                return;
            }
            this.$refs[configName + "Dialog"].dialogVisible = true;
        },

        // 关闭智能参谋窗口
        closeIntelligentAdvisor() {
            this.showIntelligentAdvisor = false;
            this.showEntityInfo = true;
        },

        // 提交实体信息
        submitEntityInfo(entityInfo) { 
            console.log("提交实体信息", entityInfo);
        },

        /**
         * 获取模型库中所有模型对应的3dModel数据
         */
        async getModel3dModel() {
            // this.model3dModel = await getModel3dModel();
        },

        /**
         * 获取模型库中所有模型对应的可视化标签
         */
        async getModelVisualizationTag() {
            // this.modelVisualizationTag = await getModelVisualizationTag();
        },

        /**
         * 获取实体树
         */
        async getEntityTree() {
            try {
                const response = await getEntityTree({ scenarioId: this.scenarioId });
                if (response.code === 200) {
                    let entityTreeData = response.data[0].commonTreeList;
                    // 区分红蓝方数据
                    this.redEntityTreeData = entityTreeData.filter(item => item.role === '1');
                    this.blueEntityTreeData = entityTreeData.filter(item => item.role === '2');
                }
            } catch (error) {
                console.error('获取实体树失败:', error);
                throw error;
            }
        },

        /**
         * 新增树节点（新增实体）
         */
        async addEntityToTree(entityInfo) { 
            // TODO调用添加接口
            
            console.log("实体信息", entityInfo);
            // 添加成功后，刷新树
            await this.getEntityTree();
            // 添加成功之后，刷新地图
            await this.addEntityToMap();
        },

        /**
         * 向地图添加实体(实体分为模型实体和名称实体)
         */
        addEntityToMap() {
            let entityTreeData = this.redEntityTreeData.concat(this.blueEntityTreeData);
            entityTreeData.forEach(entity => {
                this.addModelEntity(entity);
                this.addNameEntity(entity);
                // 处理实体的可视化效果（比如添加的是雷达，就要额外在显示一个雷达罩）
                // this.visualizationEffect(entity, this.visualAttributeList);
            });

        },

        /**
         * 添加模型实体
         * @param item 
         */
        addModelEntity(item) {
            if (graphicLayer.getGraphicById(item.selfId)) return; // 如果存在则不添加
            let modelData = JSON.parse(item.modelData);
            let isVisible = modelData["base"]["isVisible"];
            let entityType = modelData["base"]["entityType"];
            // TODO 如果添加的是卫星，位置的获取要使用其他方式
            let lla = modelData["base"]["lla"];

            let model = new mars3d.graphic.ModelPrimitive({
                id: item.selfId,
                position: new mars3d.LngLatPoint(
                    Number(lla.x),
                    Number(lla.y),
                    Number(lla.z)
                ),
                show: isVisible,
                attr: item,
                maxCacheCount: 50,
                style: {
                    uri:
                        process.env.VUE_APP_BASE_API +
                        this.onlineIconMap.model[entityType + "_" + item.sideId],
                    minimumPixelSize: 45,
                    scale: this.onlineIconMap.modelScaling[entityType],
                    show: true,
                    runAnimations: true,
                    distanceDisplayCondition: true,
                    distanceDisplayCondition_near: 0,
                    distanceDisplayCondition_far: 15000000,
                    distanceDisplayPoint: {
                        // 当视角距离超过一定距离(distanceDisplayCondition_far定义的) 后显示为点对象的样式
                        color: item.sideId == 0 ? "#FF4242" : "#2979FF",
                        pixelSize: 10,
                    },
                },
            });
            graphicLayer.addGraphic(model);
        },

        /** 添加实体名称标牌 */
        addEntityName(item) {
            if (graphicLayer.getGraphicById("entityName" + "_" + item.selfId)) return; // 如果存在则不添加
            let modelData = JSON.parse(item.modelData);

            let sideId = Number(modelData["base"]["sideId"]);
            let entityType = modelData["base"]["entityType"];
            // TODO 如果添加的是卫星，位置的获取要使用其他方式
            let lla = modelData["base"]["lla"];

            const graphic = new mars3d.graphic.LabelPrimitive({
                id: "entityName" + "_" + item.selfId,
                position: new mars3d.LngLatPoint(
                    Number(lla.x),
                    Number(lla.y),
                    Number(lla.z)
                ),
                style: {
                    text: item.label,
                    font_size: 15,
                    font_family: "黑体",
                    color: sideId == 0 ? "#FF5C5C" : "#84B5FF",
                    outline: false,
                    outlineColor: "#f1f1f1",
                    outlineWidth: 1,
                    background: true,
                    backgroundColor: "#000000",
                    backgroundOpacity: 0,
                    hasPixelOffset: true,
                    pixelOffsetY: -23,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                        0,
                        24000000
                    ), // 按视距距离显示
                    //   visibleDepth: false, // 不被遮挡
                },
            });
            graphicLayer.addGraphic(graphic);
        },

    }

};
</script>

<style lang="scss" scoped>
.scenario-build-container {
    width: 100%;
    height: 100%;
    box-sizing: border-box;

    .scenario-build-container-top {
        height: 35px;
        display: flex;
        justify-content: flex-end;
        border-bottom: 1px solid var(--ui-border-color-base);

        .scenario-build-container-top_item {
            display: flex;
            margin-right: 20px;
            align-items: center;
            font-size: var(--ui-font-size-base);
            cursor: pointer;

            .title-word {
                margin-left: 5px;
            }
        }
    }

    .scenario-build-container-bottom {
        display: flex;
        height: calc(100% - 35px);
        padding: 0 0 0 10px;

        .s-b-left {
            width: 300px;
            height: 100%;
            flex-grow: 0;
            flex-shrink: 0;
            display: flex;
            padding: 10px 10px 0 0;
            border-right: 1px solid var(--ui-border-color-split);

            .filer-box {
                min-height: 0px;
                max-height: 124px;
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;

                .filter-item {
                    width: 49%;
                    margin-top: 5px;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    .el-radio-group {
                        display: flex;
                    }
                }
            }

            .s-b-left-content {
                overflow: auto;

                .ui-tree-node-title {
                    display: flex;
                    align-items: center;
                    cursor: pointer;
                    border-radius: 5px;
                    padding-left: 5px;
                    margin-top: 10px;
                    height: 25px;
                    line-height: 25px;
                    justify-content: space-between;
                    color: var(--app-text-fg-low);

                    .ui-tree-node-title__content {
                        display: flex;
                        align-items: center;

                        .title-word {
                            margin-left: 5px;
                            font-size: var(--ui-font-size-base);
                        }
                    }

                    .ui-tree-node-title__operate {
                        display: flex;
                        align-items: center;
                        margin-right: 3px;
                        height: 24px;
                        width: 24px;

                        .ui-tree-node-title__operate-item {
                            display: none;

                            .appIcon {
                                margin: 7px 7px;
                            }

                            &:hover {
                                background-color: var(--ui-item-hover-bg);
                                border-radius: 3px;
                            }
                        }
                    }

                    &:hover {
                        background-color: var(--ui-item-hover-bg);
                        color: var(--ui-text-color);

                        .ui-tree-node-title__operate {
                            .ui-tree-node-title__operate-item {
                                display: block;

                            }
                        }
                    }
                }

                .ui-tree-node-content {
                    margin-top: 1px;
                    margin-left: 20px;
                }
            }



        }

        .s-b-middle {
            width: calc(100% - 700px);
            min-width: 450px;
            height: 100%;
            // min-height: 868px;
        }

        .s-b-right {
            width: 400px;
            height: calc(100% - 66px);
            border-left: 1px solid var(--ui-border-color-split);
        }
    }

}
</style>